/**
 * Copyright (C) 2004-2009 Jive Software. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.onlyxiahui.of.muc.iq;

import org.dom4j.Element;
import org.jivesoftware.openfire.IQHandlerInfo;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.handler.IQHandler;
import org.jivesoftware.openfire.muc.MUCRoom;
import org.jivesoftware.openfire.muc.MultiUserChatService;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.PacketError;
import org.xmpp.packet.Presence;

import com.onlyxiahui.of.muc.dao.RoomDAO;
import com.onlyxiahui.of.muc.service.RoomOfflineMessageService;

public class IQRoomOperateHandler extends IQHandler {

	// private static final Logger log =
	// LoggerFactory.getLogger(IQRoomOperateHandler.class);
	private IQHandlerInfo info;
	private String serverName;

	private static final String MODULE_NAME = "Room Operate Handler";
	private static final String NAME_SPACE = "http://www.jivesoftware.org/protocol/room#operate";
	private static final String NAME_KEY = "room";

	RoomOfflineMessageService ss = new RoomOfflineMessageService();

	public IQRoomOperateHandler() {
		super(MODULE_NAME);
		info = new IQHandlerInfo(NAME_KEY, NAME_SPACE);
	}

	@Override
	public IQ handleIQ(IQ packet) throws UnauthorizedException {
		IQ result = IQ.createResultIQ(packet);
		String userBareJid = packet.getFrom().toBareJID();// .getNode();
		JID fromJid = packet.getFrom();
		// JID toJid =packet.getTo();

		String operate = null;
		String roomName = null;
		Element pe = packet.getElement();
		Element room = pe.element("room");
		if (null != room) {
			Element m = room.element("operate");
			if (null != m) {
				operate = m.getText();
			}
			Element n = room.element("name");
			if (null != n) {
				roomName = n.getText();
			}
		}
		boolean hasJid = (null != userBareJid && !userBareJid.isEmpty());
		boolean hasName = (null != roomName && !roomName.isEmpty());

		if (!serverName.equals(packet.getFrom().getDomain()) || !hasJid || !hasName) {
			result.setChildElement(packet.getChildElement().createCopy());
			result.setError(PacketError.Condition.not_allowed);
			return result;
		}

		if ("quit".equals(operate)) {
			MultiUserChatService service = XMPPServer.getInstance().getMultiUserChatManager()
					.getMultiUserChatService("conference");
			MUCRoom mucroom = service.getChatRoom(roomName);
			if (null != mucroom) {
				long roomId = mucroom.getID();
				String nickname = RoomDAO.getNickname(roomId, userBareJid);
				String roomJid = mucroom.getJID().toBareJID();
				String to = roomJid + "/" + ((null == nickname || nickname.isEmpty()) ? userBareJid : nickname);
				String from = userBareJid;
				Presence leavePresence = new Presence(Presence.Type.unavailable);
				leavePresence.setFrom(from);
				leavePresence.setTo(to);
				service.processPacket(leavePresence);
			}
			RoomDAO.deleteUser(roomName, userBareJid);
		}
		if ("getOfflineMessage".equals(operate)) {
			ss.handlerRoomOfflineMessage01(fromJid);
		}

		if ("add".equals(operate)) {
			if (null != room) {
				Element n = room.element("jid");
				if (null != n) {
					String jid = n.getText();
				}
			}
		}
		result.setChildElement(packet.getChildElement().createCopy());
		return result;
	}

	@Override
	public IQHandlerInfo getInfo() {
		return info;
	}

	@Override
	public void initialize(XMPPServer server) {
		super.initialize(server);
		serverName = server.getServerInfo().getXMPPDomain();
	}
}
